package study.alibaba.sentinel.support.rule;

import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 限流规则
 */
@Slf4j
public class FlowRuleInitFunc implements InitFunc {

    @Override
    public void init() throws Exception {
        List<FlowRule> ruleLt = Lists.newArrayList();
        FlowRule rule = new FlowRule();

        //资源名
        rule.setResource("sayHi");
        //来源，若为 default 则不区分调用来源
        rule.setLimitApp("default");
        //阈值类型（QPS 或 并发线程数）
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //阈值
        rule.setCount(1);
        //是否集群
        rule.setClusterMode(false);
        //流控模式（直接、关联、链路）
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
        //流控效果（快速失败、Warm Up、排队等待）
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);

        ruleLt.add(rule);

        log.info("load _1_flow rule");
        FlowRuleManager.loadRules(ruleLt);
    }
}
